package com.chixing.xml_parse;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.sound.midi.Soundbank;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class SAXParseDemo extends DefaultHandler {

    private String xmlFilePath = "D:\\xxxx.xml";

    public SAXParseDemo() {
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser = null;
        try {
            saxParser = parserFactory.newSAXParser();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void startDocument() throws SAXException {
        System.out.println("XML文档开始解析");
        super.startDocument();
    }

    @Override
    public void endDocument() throws SAXException {
        System.out.println("XML文档结束解析");
        super.endDocument();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.println("qname:"+qName);
        if (attributes !=null&&attributes.getLength()>0){
            for (int i = 0; i < attributes.getLength(); i++) {
                String attrName = attributes.getQName(i);
                String attrValue = attributes.getValue(i);
                System.out.println(attrName + ":" + attrValue);
            }
            System.out.println();
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        System.out.println(new String(ch,start,length).trim());
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {

    }

    public static void main(String[] args) {
        new SAXParseDemo();
    }
}
